import { defineStore } from 'pinia'
import type { User } from '@/types/user'
import { authApi } from '@/api/modules/auth'
import TokenManager from '@/utils/auth'
import { ElMessage } from 'element-plus'

interface UserState {
  userInfo: User | null
  token: string | null
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: null,
    token: TokenManager.getAccessToken()
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userId: (state) => state.userInfo?.id || null
  },

  actions: {
    // 登录
    async login(credentials: { username: string; password: string }) {
      try {
        const response = await authApi.login(credentials)
        // 响应拦截器已经返回了 { code: 0, message: "...", data: {...} }
        const { accessToken, refreshToken, user } = response.data

        this.token = accessToken
        this.userInfo = {
          id: user.id,
          username: user.username,
          name: user.nickname,
          avatar: user.avatar || '',
          role: user.role,
          email: user.email,
          phone: user.phone,
          createdAt: user.createdAt,
          updatedAt: user.updatedAt
        }

        TokenManager.setAccessToken(accessToken)
        TokenManager.setRefreshToken(refreshToken)
        return true
      } catch (error) {
        console.error('登录错误:', error)
        ElMessage.error('登录失败，请检查用户名和密码')
        return false
      }
    },

    // 登出
    async logout() {
      try {
        // 调用后端退出登录接口
        await authApi.logout()
      } catch (error) {
        // 忽略退出登录接口的错误
        console.error('Logout API error:', error)
      } finally {
        // 清除本地状态
        this.userInfo = null
        this.token = null
        TokenManager.removeAccessToken()
        TokenManager.removeRefreshToken()
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await authApi.getUserInfo()
        const userInfo = response.data

        this.userInfo = {
          id: userInfo.id,
          username: userInfo.username,
          name: userInfo.nickname,
          avatar: userInfo.avatar,
          role: userInfo.role,
          email: userInfo.email,
          phone: userInfo.phone,
          createdAt: userInfo.createdAt,
          updatedAt: userInfo.updatedAt
        }

        return true
      } catch (error) {
        this.logout()
        return false
      }
    },

    // 修改密码
    async changePassword(oldPassword: string, newPassword: string) {
      try {
        await authApi.changePassword({ oldPassword, newPassword })
        ElMessage.success('密码修改成功')
        return true
      } catch (error) {
        ElMessage.error('密码修改失败')
        return false
      }
    },

    // 更新个人资料
    async updateProfile(data: any) {
      try {
        await authApi.updateProfile(data)
        // 更新用户信息
        if (this.userInfo) {
          Object.assign(this.userInfo, {
            name: data.nickname || this.userInfo.name,
            email: data.email || this.userInfo.email,
            phone: data.phone || this.userInfo.phone,
            avatar: data.avatar || this.userInfo.avatar
          })
        }
        ElMessage.success('个人资料更新成功')
        return true
      } catch (error) {
        ElMessage.error('个人资料更新失败')
        return false
      }
    }
  }
})
